﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace HousingDistribution
{
    class InfoSearcher
    {
        //考虑unit可能发生变化，能否作为去处重复信息的标准？
        public bool PersonExisted(PersonInfo info)
        {
            StringBuilder sqlCheck = new StringBuilder("select * from person where name='");
            sqlCheck.Append(info.name);
            sqlCheck.Append("' and sex='");
            sqlCheck.Append(info.sex);
            sqlCheck.Append("' and unit ='");
            sqlCheck.Append(info.unit);
            sqlCheck.Append("' and mateName='");
            sqlCheck.Append(info.mateInfo.name);
            sqlCheck.Append("'");

            if (RecordExisted(sqlCheck.ToString()))
                return true;
            else
                return false;
        }

        public int GetPersonId(PersonInfo info)
        {
            StringBuilder sqlCheck = new StringBuilder("select idperson from person where name='");
            sqlCheck.Append(info.name);
            sqlCheck.Append("' and sex='");
            sqlCheck.Append(info.sex);
            sqlCheck.Append("' and unit ='");
            sqlCheck.Append(info.unit);
            sqlCheck.Append("' and mateName='");
            sqlCheck.Append(info.mateInfo.name);
            sqlCheck.Append("'");

            try
            {
                DataSet ds = DBProc.Instance().ReadData(sqlCheck.ToString());

                if (ds != null && ds.Tables.Count > 0)
                {
                    DataTable dt = ds.Tables[0];
                    if (dt.Rows.Count == 1)
                    {
                        object[] elements = dt.Rows[0].ItemArray;
                        return (int)elements[0];
                    }
                }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
                //发生异常时，则认为记录存在，防止错误记录入库
                return 0;
            }

            return 0;
        }

        private bool RecordExisted(string sql)
        {
            try
            {
                DataSet ds = DBProc.Instance().ReadData(sql);

                if (ds != null && ds.Tables.Count > 0)
                {
                    DataTable dt = ds.Tables[0];
                    if (dt.Rows.Count > 0)
                        return true;
                }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
                //发生异常时，则认为记录存在，防止错误记录入库
                return true;
            }

            return false;
        }


        String PERSON_TYPE_COL = DataDictionary.Instance().PersonTableFieldName(PersonColConsts.TYPE);
        String DGV_TYPE_NAME_COL = DataDictionary.Instance().DGVNewColName(DGVNewColConsts.PERSON_TYPE_NAME);
    }
}
